package heima_bixiangdong.pro_con;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// Condition实例代码
class BoundedBuffer {
    final Lock lock = new ReentrantLock();
    final Condition notFull = lock.newCondition(); // 负责生产
    final Condition notEmpty = lock.newCondition(); // 负责消费

    final Object[] items = new Object[20];
    int putptr, takeptr, count;

    public void put(Object x) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length) {
                //System.out.println(Thread.currentThread().getName() + "生产者等待");
                notFull.await();
            }
            items[putptr] = x;
            //System.out.println(Thread.currentThread().getName() + "生产" + x + "--->" + (putptr + 1));
            if (++putptr == items.length) putptr = 0;
            ++count;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                //System.out.println(Thread.currentThread().getName() + "消费者等待");
                notEmpty.await();
            }
            Object x = items[takeptr];
            //System.out.println(Thread.currentThread().getName() + "消费" + x + "..." + (takeptr + 1));
            if (++takeptr == items.length) takeptr = 0;
            --count;
            notFull.signal();
            return x+""+(takeptr+1);
        } finally {
            lock.unlock();
        }
    }
}

public class LockDemo2 {
    public static void main(String[] args) {
        BoundedBuffer boundedBuffer = new BoundedBuffer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        boundedBuffer.put("面包");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "Thread-A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Object take = boundedBuffer.take();
                        System.out.println(Thread.currentThread().getName()+"消费面包"+take);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "Thread-B").start();
    }
}
